package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"

	"gitee.com/wu-jin-feng/fgin"
	reflectPb "gitee.com/wu-jin-feng/fgin/demos/fconsul_test/server/pb"
	"gitee.com/wu-jin-feng/fgin/fgin_plugs/fotel/ftracer"
	"google.golang.org/grpc/metadata"
)

type DemoServiceServer struct {
	reflectPb.UnimplementedDemoServiceServer
}

func (s *DemoServiceServer) GetScheme(ctx context.Context, req *reflectPb.GetSchemeReq) (*reflectPb.GetSchemeResp, error) {
	md, _ := metadata.FromIncomingContext(ctx)
	for k, vLs := range md {
		for _, v := range vLs {
			ctx = metadata.AppendToOutgoingContext(ctx, k, v)
		}
	}
	fmt.Println("server md is: ", md)
	if req.Info == nil {
		return nil, errors.New("info 不能为空")
	}
	grpcConn, err := f.GetFgrpcClientConn("fjaeger_test_grpc_server1")
	if err != nil {
		return nil, err
	}
	c := reflectPb.NewDemoServiceClient(grpcConn)
	res, err := c.GetScheme(ctx, &reflectPb.GetSchemeReq{
		Path: "321222",
		Info: &reflectPb.GetSchemeRespInfo{
			Info: "哈哈哈哈",
			Name: "gogo",
		},
	})
	if err != nil {
		return nil, err
	}
	req1, _ := http.NewRequest("GET", "http://localhost:8013/test", nil)
	req1.Header = ftracer.HttpInject(ctx, req1.Header)
	_, err = (&http.Client{}).Do(req1)
	if err != nil {
		return nil, err
	}
	endData := &reflectPb.GetSchemeResp{
		Data: req.Path + ",gogogo",
		Info: &reflectPb.GetSchemeRespInfo{
			Info: fmt.Sprintf("这是一个info,%s; server1:%s", req.Info.Info, res.Info.Info),
			Name: fmt.Sprintf("作者是%s,; server1:%s", req.Info.Name, res.Info.Name),
		},
	}
	return endData, nil
}

var f = fgin.Fgin{}

func main() {
	s := f.GetGrpcServer("./test.yaml")
	reflectPb.RegisterDemoServiceServer(s, &DemoServiceServer{})
	f.RunGrpc(s)
}
